package cn.feng.thinkInJava.a9_1_类型信息.typeinfo.a14_03_03;
//: typeinfo/PetCount.java
// Using instanceof.
import static net.mindview.util.Print.print;
import static net.mindview.util.Print.printnb;

import java.util.HashMap;

import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.Cat;
import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.Dog;
import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.Hamster;
import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.Manx;
import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.Mouse;
import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.Mutt;
import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.Pet;
import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.Pug;
import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.Rat;
import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.Rodent;
import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.a14_03_00.PetCreator;
import cn.feng.thinkInJava.a9_1_类型信息.typeinfo.pets.a14_03_01.ForNameCreator;

/**
 * @author fengyu
 * @date  2015年8月9日
 */
public class PetCount {
  static class PetCounter extends HashMap<String,Integer> {
    public void count(String type) {
      Integer quantity = get(type);
      if(quantity == null)
        put(type, 1);
      else
        put(type, quantity + 1);
    }
  }	
  public static void
  countPets(PetCreator creator) {
    PetCounter counter= new PetCounter();
    for(Pet pet : creator.createArray(20)) {
      // List each individual pet:
      printnb(pet.getClass().getSimpleName() + " ");
      //instanceof有比较严格的箱子:只可将其与命名类型进行比较,而不能与Class对象比较
      if(pet instanceof Pet)
        counter.count("Pet");
      if(pet instanceof Dog)
        counter.count("Dog");
      if(pet instanceof Mutt)
        counter.count("Mutt");
      if(pet instanceof Pug)
        counter.count("Pug");
      if(pet instanceof Cat)
        counter.count("Cat");
      if(pet instanceof Manx)
        counter.count("EgyptianMau");
      if(pet instanceof Manx)
        counter.count("Manx");
      if(pet instanceof Manx)
        counter.count("Cymric");
      if(pet instanceof Rodent)
        counter.count("Rodent");
      if(pet instanceof Rat)
        counter.count("Rat");
      if(pet instanceof Mouse)
        counter.count("Mouse");
      if(pet instanceof Hamster)
        counter.count("Hamster");
    }
    // Show the counts:
    print();
    print(counter);
  }	
  public static void main(String[] args) {
    countPets(new ForNameCreator());
  }
} /* Output:
Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug Mouse Cymric
{Pug=3, Cat=9, Hamster=1, Cymric=7, Mouse=2, Mutt=3, Rodent=5, Pet=20, Manx=7, EgyptianMau=7, Dog=6, Rat=2}
*///:~
